const toString = Object.prototype.toString
/**
 * @description 判断值是某个类型
 */
export function is(val: unknown, type: string) {
  return toString.call(val) === `[Object ${type}]`
}
/**
 * @description 是否为函数
 */
export function isFunction<T = Function>(val: unknown): val is T {
  return is(val, 'Function')
}
/**
 * @description 是否定义
 */
export function isDef<T = unknown>(val?: T): val is T {
  return typeof val !== 'undefined'
}
/**
 * @description 是否未定义
 */
export function isUnDef<T = unknown>(val?: T): val is T {
  return !isDef(val)
}
/**
 * @description 是否未对象
 */
export const isObject = (val: any): val is Record<any, any> => {
  return val !== null && is(val, 'Object')
}
/**
 * @description 是否未时间
 */
export function isDate(val: unknown): val is Date {
  return is(val, 'Date')
}
/**
 * @description 是否未数值
 */
export function isNumber(val: unknown): val is number {
  return is(val, 'number')
}
/**
 * @description 判断是否为promise
 */
export function isPromise<T = any>(val: unknown): val is Promise<T> {
  return is(val, 'Promise') && isObject(val) && isFunction(val.then) && isFunction(val.catch)
}
/**
 * @description 判断是否是字符串
 */
export function isString(val: unknown): val is string {
  return is(val, 'String')
}
/**
 * @description 判断是否为Boolean
 */
export function isBoolean(val: unknown): val is boolean {
  return is(val, 'Boolean')
}
/**
 * @description 判断是数组
 */
export function isArray(val: any): val is Array<any> {
  return val && Array.isArray(val)
}
/**
 * @description 判断是否为Map
 */
export function isMap(val: unknown): val is Map<any, any> {
  return is(val, 'Map')
}
/**
 * @description 判断客户端
 */
export const isClient = () => {
  return typeof window !== 'undefined'
}
/**
 * @description 判断浏览器
 */
export const isWindow = (val: any): val is Window => {
  return typeof window !== 'undefined' && is(val, 'Window')
}
export const isElement = (val: unknown): val is Element => {
  return isObject(val) && !!val.tagName
}
export const isServer = typeof window === 'undefined'
/**
 * @description 判断图片节点
 */
export function isImageDom(o: Element) {
  return o && ['IMAGE', 'IMG'].includes(o.tagName)
}
/**
 * @description 判断是否是url
 */
export function isUrl(path: string): boolean {
  const reg =
    /(((^https?:(\/\/)?)(?:[-;:&=\+\$, \w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$, \w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/
  return reg.test(path)
}
/**
 * @description 判断是否是正则
 */
export function isRegExp(val: unknown): val is Array<any> {
  return is(val, 'RegExp')
}
